package com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.tag;

import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.audaque.springboot.foshanupload.web.exception.RException;
import com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.tag.model.IegTagVo;
import com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.token.IegTokenProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class IegTagProvider {


    @Autowired
    private IegTagProperties iegTagProperties;

    @Autowired
    private IegTokenProvider iegTokenProvider;
    @Autowired
    private ObjectMapper objectMapper;

    public IegTagVo getList(String name) throws Exception {
        return getList(name, false);
    }

    private IegTagVo getList(String name, Boolean retryedYn) throws Exception {
        String tokenKey = iegTagProperties.getTokenKey();
        String url = iegTagProperties.getListUrl(name);
        String v2Token = iegTokenProvider.getV2Token();
        log.debug("ieg获取标签列表接口 1000086 调用中");
        String result = null;
        try {
            result = HttpRequest.get(url)
                    .header(tokenKey, v2Token)
                    .execute().body();
        } catch (Exception e) {
            throw new RException("ieg获取标签列表接口 调用过程中异常 1000086 %s",e.getMessage());
        }
        if (StringUtils.isBlank(result)) {
            throw new RException("ieg获取标签列表接口 响应异常 1000086 无响应");
        }
        log.debug("ieg获取标签列表接口 1000086 result {}" ,result);
        IegTagVo rsp = null;
        try {
            rsp = (IegTagVo) objectMapper.readerFor(IegTagVo.class).readValue(result);
        } catch (Exception e) {
            throw new RException("ieg获取标签列表接口 反序列化异常 1000086 %s", e.getMessage());
        }
        if (rsp!=null&&rsp.getCode() != null) {
            if (!retryedYn && !iegTokenProvider.authorize(v2Token)) {
                iegTokenProvider.setV2Token(null);
                getList(name, true);
            }
            throw new RException("ieg获取标签列表接口 响应异常 %s", rsp.getMsg());
        }
        return rsp;

    }


}
